//
//  BatteryView.m
//  BalanceCar
//
//  Created by 郑信鸿 on 17/6/27.
//  Copyright © 2017年 郑信鸿. All rights reserved.
//

#import "BatteryView.h"


@implementation BatteryView{
    
    UIColor *_batteryRedColor;
    UIColor *_batteryGreenColor;
    CALayer *_batterLayer;
    CGFloat _viewHeight;
    CGFloat _viewWidth;
}


- (instancetype)init{
    
    if (self = [super init]) {
       
        _viewWidth = 80.0;
        _viewHeight = 30.0;
       
        UIImageView *innerImage = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"fun_battery_ inner"]];
        [self addSubview:innerImage];
        [innerImage mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.mas_offset(0);
        }];
        _batterLayer = [[CALayer alloc] init];
        [self.layer addSublayer:_batterLayer];
        UIImageView *batteryImage = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"fun_battery_body"]];
        [self addSubview:batteryImage];
        [batteryImage mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.mas_offset(0);
        }];
        _batteryRedColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"fun_battery_red"]];
        _batteryGreenColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"fun_battery_green"]];
       
        
    }
    return self;
}


- (void)setBatteryPercentage:(CGFloat)batteryPercentage{
    _batteryPercentage = batteryPercentage;
    UIColor *batteryColor = _batteryGreenColor;
    if (batteryPercentage < 0.2) {
        batteryColor = _batteryRedColor;
    }
    CGFloat width = _viewWidth * batteryPercentage;
    CGFloat x = _viewWidth - width;
    CGFloat y = (_viewHeight - 20)/2;
    _batterLayer.frame = CGRectMake(x, y, width,20);
    _batterLayer.backgroundColor = batteryColor.CGColor;
}

@end
